# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import urllib2
from deal_info_api import *

 
def deal_info_time(f_xml, subdeal, li_from, li_to, tabsum, hms):
    subdeal_li = subdeal.getiterator(li_from)

    zt = subdeal_li[0].text

    year = zt.split('年'.decode('utf-8'))
    month = year[1].split('月'.decode('utf-8'))
    day = month[1].split('日'.decode('utf-8'))

    f_xml.write(('\t' * tabsum + '<%s>%s-%s-%s %s+0800</%s>\n' % (li_to, year[0], month[0], day[0], hms, li_to)).encode('utf-8'))

def deal_info_url(f_xml, deal, city_enname):
    deal_id = deal.getiterator('id')
    f_xml.write('\t' * 2 + '<url>http://t.58.com/home/%s/%s</url>\n' % (city_enname, deal_id[0].text))

def deal_city(tuan, city_node, city, city_id, city_enname):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = city_node.getiterator('product')
    for deal in deals:
	if judge(f_id, d_id, deal, 'id'):
	    continue

	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, '58', '58同城'.decode('utf-8'), 'http://t.58.com/', 'http://t.58.com/')
    	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, deal, 'id', 'id', 2)
	deal_info_add(f_xml, deal, 'name', 'name', 2)
	deal_info_cats(f_xml, deal, 'name')
	deal_info_vendor_1(f_xml, deal)
	deal_info_time(f_xml, deal, 'begin_date', 'start_time', 2, '00:00:00')
	deal_info_time(f_xml, deal, 'end_date', 'end_time', 2, '23:59:59')
	deal_info_add(f_xml, deal, 'market_price', 'o_price', 2)
	deal_info_add(f_xml, deal, 'group_price', 'c_price', 2)
	deal_info_discount_and_save_money(f_xml, deal, 'group_price', 'market_price')
	deal_info_img(f_xml, deal, 'image')
	deal_info_url(f_xml, deal, city_enname)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)



city_list = open('%slist/citylist' % (get_home_dir()), 'r')
cities = eval(city_list.read())

f_url = urllib2.urlopen('http://t.58.com/api/products')

root_url = ET.fromstring(f_url.read())

root = root_url.getiterator('city')
for node in root:
    city_id = node.getiterator('id')
    city_name = node.getiterator('name')
    city_listname = node.getiterator('listname')
    try:
    	deal_city('58', node, cities[city_name[0].text.encode('utf-8')], city_id[0].text, city_listname[0].text)
    except KeyError:
	os.system(('date >> %serror.log && echo "%s KeyError: %s\n" >> %serror.log' % (get_home_dir(), '58', city_name[0].text)).encode('utf-8'), get_home_dir())
